/* eslint-disable import/no-unresolved */
/* eslint-disable import/extensions */
const app = getApp();
const { AskComponent } = app._require("common/index");
const { uploadFile } = app._require("utils/upload.file");
import dragMixin from "./drag.mixin.js";
import authMixin from "./auth.mixin.js";

AskComponent({
    behaviors: [dragMixin, authMixin],
    properties: {
        fileList: {
            type: Array,
            value: [],
            observer: "formatFileList",
        },
        forDisplay: {
            type: Boolean,
            value: false,
        },
        props: {
            type: Object,
            value: {
                dir: "", // 服务器相对路径
                suffix: "png", // 图片后缀
                limit: 10 * 1024 * 1024, // 图片后缀
            },
        },
        dragModel: {
            type: Boolean,
            value: false,
        },
        action: {
            type: String,
            value: "",
        },
        uploadType:{
            type: String,
            value: "",
        },
    },
    data: {
        fileId: 0,
        list: [],
   
    },
    methods: {
        formatFileList() {
            const { fileList = [] } = this.data;
            if (fileList.length === 0) {
                this.data.fileId = 0;
                this.setData({ list: [] });
                return;
            }
            const fileInList = cur => this.data.list.findIndex(c => c.fileName === cur.fileName) === -1;
            let list = fileList.filter(cur => fileInList(cur) || !cur._id);
            if (list.length === 0) {
                return;
            }
            list = list.map(cur => ({
                ...cur,
                _id: this.data.fileId++ + "start",
            }));
            if (this.data.list.length !== fileList.length - list.length) {
                this.setData({ list: [] });
            }
            this.formatRenderList(list);
            this.triggerEvent("update", {
                type: "init",
                list: this.data.list,
            });
        },
        handleDelClick(e) {
            const { index } = e.currentTarget.dataset;
            const _list = this.data.list;
            const _item = _list[index];
            _list.splice(index, 1);
            this.setData({ list: _list });
            this.triggerEvent("update", {
                type: "remove",
                list: _list,
                item: _item,
            });
        },
        previewImage(e) {
            const _list = this.data.list.map(cur => cur.src || cur.filePath);
            const { item } = e.currentTarget.dataset;
            wx.previewImage({
                current: item.src || item.filePath, // 当前显示图片的http链接
                urls: _list || [], // 需要预览的图片http链接列表
            });
        },
        chooseImage() {

        
            const num = this.data.props.num || 0;
            console.log(num);
            wx.chooseImage({
                count: num === 0 || num > 9 ? 9 : num, // 默认最多一次选择9张图
                sizeType: ["original", "compressed"], // 可以指定是原图还是压缩图，默认二者都有
                sourceType: ["album", "camera"], // 可以指定来源是相册还是相机，默认二者都有
                success: res => {
                    console.log(res);
                    const tempFiles = res.tempFiles;
                    this.upload(tempFiles);
                },
                fail() {
                    // wx.hideLoading();
                },
            });
        },
        async upload(files) {





            wx.showLoading({
                title: "上传中...",
                mask: true,
            });
            try {
          
                let uploadType = this.data.uploadType;
                if(uploadType == 'sb_report'){
                    //小程序上报
                    uploadType =  "declare-data";
                }else{
                    uploadType = "form-data";
                }
                const nowTime = new Date();
                const uploadFilePath = uploadType+"/img"+"/"+nowTime.format("yyyy-MM-dd")+"/"

                
                const uploadList = files.map(file => ({
                    dir: uploadFilePath,//this.data.props.dir + nowTime.format("yyyy/MM/dd") + "/",
                    filePath: file.path || "",
                    size: file.size,
                    _id: this.data.fileId++ + "choose",
                }));
                this.formatRenderList(uploadList);
                const _response = await uploadFile(uploadList, {
                    limit: this.data.props.limit,
                    timeout: this.data.props.timeout,
                    action: this.data.action,
                    initAuth: this.getCredentials.bind(this),
                    onReady: files => {
                        files.map(cur => {
                            this.updateListStatus(cur);
                        });
                        this.triggerEvent("update", {
                            type: "upload",
                            list: files,
                            item: null,
                        });
                    },
                    beforeUpload: (curFile, files) => {
                        this.updateListStatus(curFile);
                        this.triggerEvent("update", {
                            type: "upload",
                            list: files,
                            item: curFile,
                        });
                    },
                    afterUpload: (curFile, files, errors) => {
                        if (errors && errors.length > 0) {
                            wx.askShowToastEx({
                                icon: "none",
                                title: "上传文件只能在" + this.data.props.limit / 1024 / 1024 + "M以内",
                            });
                        }
                        this.updateListStatus(curFile);
                        this.triggerEvent("update", {
                            type: "upload",
                            list: files,
                            item: curFile,
                        });
                    },
                });
                wx.hideLoading();
                console.log(_response);
                this.triggerEvent("updateEnd", this.data.list);
            } catch (error) {
                this.data.list.map(cur => {
                    this.updateListStatus({
                        ...cur,
                        status: cur.status === "pending" ? "fail" : cur.status,
                    });
                });
                wx.hideLoading();
                console.log(error);
            }
        },
        updateListStatus(cur) {
            const _index = this.data.list.findIndex(item => item._id === cur._id);
            if (_index !== -1) {
                this.setData({
                    ["list[" + _index + "]"]: {
                        ...this.data.list[_index],
                        ...cur,
                    },
                });
            }
        },
        formatRenderList(list) {
            const num = this.data.props.num || 0;
            let _list = [];
            _list = this.data.list.concat(list);
            _list = num === 0 || _list.length < num ? _list : _list.slice(_list.length - num);
            this.setData({ list: _list });
        },
    },
});
